package ru.elifantiev.cityrouter;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import ru.elifantiev.cityrouter.util.AssetProvider;

import java.io.IOException;

public class WebDemoActivity extends Activity {

    private WebView view;
    private String TAG = "WebDemoActivity";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_demo);

        String data;


        view = (WebView)findViewById(R.id.webview);
        view.getSettings().setJavaScriptEnabled(true);
        view.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                AssetManager assets = WebDemoActivity.this.getAssets();
                try {
                    String[] jsFiles = assets.list("mapDemo");
                    for (String file : jsFiles)
                        execJSCommand(AssetProvider.getStringAsset(assets, "mapDemo/" + file));
                } catch (IOException e) {
                    Log.e(TAG, "Error while loading JS-assets", e);
                }
                execJSCommand("console.log(123);");
                execJSCommand("done();");
            }
        });

        try {
            data = AssetProvider.getStringAsset(this.getAssets(), "indexDemo.html");
        } catch (IOException e) {
            data = "fail!";
        }

        view.loadDataWithBaseURL(
                "http://transport.elifantiev.ru/",
                data,
                "text/html",
                "UTF-8",
                "http://transport.elifantiev.ru/");
    }

    private void execJSCommand(String command) {
        view.loadUrl("javascript:" + command);
    }
}